package com.lestv.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import android.util.Log;


public class UploadUtil {
	/**
	 * 直接通过HTTP协议提交数据到服务器,实现表单提交功能
	 * 
	 * @param actionUrl
	 *            上传路径
	 * @param params
	 *            请求参数 key为参数名,value为参数值
	 * @param file
	 *            上传文件
	 */
	public static InputStream post(String actionUrl,Map<String, String> params, FormFile file) {
		try {
			String BOUNDARY = "---------------------------7db2b3110880"; // 数据分隔线
			String MULTIPART_FORM_DATA = "multipart/form-data";
			int len = 0;

			StringBuilder sb = new StringBuilder();

			// 上传的表单参数部分，格式请参考文章
			
			for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
				Log.i("T", "value" + entry.getValue());
				sb.append("--");
				sb.append(BOUNDARY);
				sb.append("\r\n");
				sb.append("Content-Disposition: form-data; name=\""
						+ entry.getKey() + "\"\r\n\r\n");
				sb.append(entry.getValue());
				sb.append("\r\n");
			}
		
			StringBuilder split = new StringBuilder();
			split.append("--");
			split.append(BOUNDARY);
			split.append("\r\n");
			split.append("Content-Disposition: form-data;name=\""
					+ file.getFormname() + "\";filename=\""
					+ file.getFilname() + "\"\r\n");
			split.append("Content-Type: " + file.getContentType()
					+ "\r\n\r\n");
			
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("--");
			stringBuilder.append(BOUNDARY);
			stringBuilder.append("\r\n");
			stringBuilder.append("Content-Disposition: form-data; name=\"isdefault\"\r\n\r\n");
			stringBuilder.append(0);
			
			byte[] end_data = ("--"+BOUNDARY + "–-\r\n").getBytes();// 数据结束标志
			len = sb.toString().getBytes().length+split.toString().getBytes().length+file.getData().length+end_data.length+stringBuilder.toString().getBytes().length+("\r\n").getBytes().length+("\r\n").getBytes().length;
			Log.i("T", sb.toString()+split.toString()+stringBuilder.toString()+("\r\n")+("--"+BOUNDARY + "--"+"\r\n"));
			Log.i("T", "lenth--"+len);
			URL url = new URL(actionUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false);// 不使用Cache
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
					+ "; boundary=" + BOUNDARY);
			conn.setRequestProperty("Content-Length", String.valueOf(len));
			DataOutputStream outStream = new DataOutputStream(
					conn.getOutputStream());
			outStream.write(sb.toString().getBytes());// 发送表单字段数据
			outStream.write(split.toString().getBytes());
			outStream.write(file.getData(), 0, file.getData().length);
			outStream.write("\r\n".getBytes());
		
			outStream.write(stringBuilder.toString().getBytes());
			outStream.write("\r\n".getBytes());
			outStream.write(end_data);
			outStream.flush();
			outStream.close();
			Log.i("T", "数据发送完毕");
			Log.i("T", "response message" + conn.getResponseMessage());
			int cah = conn.getResponseCode();
			Log.i("T", "responsecode=" + cah);
			InputStream is = null;
			if(cah==200){
				is = conn.getInputStream();
			}
			if (cah != 200)
				throw new RuntimeException("请求url失败");
			

			return is;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		return outSteam.toByteArray();
	}

}
